package com.zuo_book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zuo_book.common.BusinessException;
import com.zuo_book.common.ResultCode;
import com.zuo_book.common.SecurityUtils;
import com.zuo_book.dto.SysProjectDTO;
import com.zuo_book.entity.*;
import com.zuo_book.mapper.SysProjectMapper;
import com.zuo_book.mapper.SysProjectMemberMapper;
import com.zuo_book.mapper.SysProjectStageMapper;
import com.zuo_book.mapper.UserMapper;
import com.zuo_book.service.SysProjectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目管理服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysProjectServiceImpl implements SysProjectService {

    private final SysProjectMapper projectMapper;
    private final SysProjectMemberMapper projectMemberMapper;
    private final SysProjectStageMapper sysProjectStageMapper;
    private final UserMapper userMapper;
    private final SysProjectMapper sysProjectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProject(SysProjectBo projectBo) {

        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();

        // 设置创建者
        projectBo.setCreateBy(userId);

        // 设置初始状态和进度
        if (projectBo.getStatus() == null) {
            projectBo.setStatus(0); // 进行中
        }
        if (projectBo.getProgress() == null) {
            projectBo.setProgress(0); // 0%
        }

        SysProject project = new SysProject();
        BeanUtils.copyProperties(projectBo, project);
        project.setCreateTime(LocalDateTime.now());
        project.setCreateBy(userId);

        // 插入项目
        projectMapper.insert(project);

        projectBo.getStages().forEach(stage -> {
            stage.setProjectId(project.getId());
            stage.setCreateTime(LocalDateTime.now());
            sysProjectStageMapper.insert(stage);
        });

        // 添加创建者为项目成员
        SysProjectMember member = new SysProjectMember();
        member.setProjectId(project.getId());
        member.setUserId(userId);
        member.setRoleType(0); // 创建者
        member.setJoinTime(LocalDateTime.now());
        projectMemberMapper.insert(member);

        return project.getId();
    }

    @Override
    public void updateProject(SysProject project) {
        // 检查项目是否存在
        SysProject existingProject = projectMapper.selectById(project.getId());
        if (existingProject == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED.getCode(), "项目不存在");
        }

        // 更新项目
        projectMapper.updateById(project);
    }

    @Override
    public SysProjectDTO getProjectById(Long projectId) {
        // 获取项目信息
        SysProject project = projectMapper.selectById(projectId);
        if (project == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED.getCode(), "项目不存在");
        }

        // 转换为DTO
        SysProjectDTO projectDTO = new SysProjectDTO();
        BeanUtils.copyProperties(project, projectDTO);

        // 获取创建者信息
        User creator = userMapper.selectById(project.getCreateBy());
        if (creator != null) {
            projectDTO.setCreateByName(creator.getUsername());
        }

        return projectDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProject(Long projectId) {
        // 检查项目是否存在
        SysProject project = projectMapper.selectById(projectId);
        if (project == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED.getCode(), "项目不存在");
        }

        // 删除项目成员
        LambdaQueryWrapper<SysProjectMember> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(SysProjectMember::getProjectId, projectId);
        projectMemberMapper.delete(memberWrapper);

        // 删除项目
        projectMapper.deleteById(projectId);
    }

    @Override
    public Page<SysProjectDTO> listProjects(int page, int size, String keyword) {
        // 创建分页对象
        Page<SysProject> pageParam = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<SysProject> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(SysProject::getProjectName, keyword)
                   .or()
                   .like(SysProject::getProjectCode, keyword)
                   .or()
                   .like(SysProject::getDescription, keyword);
        }
        wrapper.orderByDesc(SysProject::getCreateTime);

        // 执行查询
        Page<SysProject> projectPage = projectMapper.selectPage(pageParam, wrapper);

        // 转换为DTO
        List<SysProjectDTO> projectDTOList = new ArrayList<>();
        for (SysProject project : projectPage.getRecords()) {
            SysProjectDTO projectDTO = new SysProjectDTO();
            BeanUtils.copyProperties(project, projectDTO);

            // 获取创建者信息
            User creator = userMapper.selectById(project.getCreateBy());
            if (creator != null) {
                projectDTO.setCreateByName(creator.getUsername());
            }

            projectDTOList.add(projectDTO);
        }

        // 创建返回结果
        Page<SysProjectDTO> result = new Page<>();
        result.setCurrent(projectPage.getCurrent());
        result.setSize(projectPage.getSize());
        result.setTotal(projectPage.getTotal());
        result.setRecords(projectDTOList);

        return result;
    }

    @Override
    public void updateProjectStatus(Long projectId, Integer status) {
        // 检查项目是否存在
        SysProject project = projectMapper.selectById(projectId);
        if (project == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED.getCode(), "项目不存在");
        }

        // 更新状态
        SysProject updateProject = new SysProject();
        updateProject.setId(projectId);
        updateProject.setStatus(status);
        projectMapper.updateById(updateProject);
    }

    @Override
    public void updateProjectProgress(Long projectId, Integer progress) {
        // 检查项目是否存在
        SysProject project = projectMapper.selectById(projectId);
        if (project == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED.getCode(), "项目不存在");
        }

        // 检查进度范围
        if (progress < 0 || progress > 100) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED.getCode(), "进度必须在0-100之间");
        }

        // 更新进度
        SysProject updateProject = new SysProject();
        updateProject.setId(projectId);
        updateProject.setProgress(progress);
        projectMapper.updateById(updateProject);
    }

    @Override
    public Page<SysProjectDTO> getUserProjects(Long userId, int page, int size) {
        // 创建分页对象
        Page<SysProject> pageParam = new Page<>(page, size);

        // 查询用户参与的项目ID列表
        LambdaQueryWrapper<SysProjectMember> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(SysProjectMember::getUserId, userId);
        List<SysProjectMember> members = projectMemberMapper.selectList(memberWrapper);
        List<Long> projectIds = members.stream().map(SysProjectMember::getProjectId).collect(Collectors.toList());

        if (projectIds.isEmpty()) {
            // 用户没有参与任何项目
            Page<SysProjectDTO> result = new Page<>();
            result.setCurrent(pageParam.getCurrent());
            result.setSize(pageParam.getSize());
            result.setTotal(0);
            result.setRecords(new ArrayList<>());
            return result;
        }

        // 构建查询条件
        LambdaQueryWrapper<SysProject> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysProject::getId, projectIds);
        wrapper.orderByDesc(SysProject::getCreateTime);

        // 执行查询
        Page<SysProject> projectPage = projectMapper.selectPage(pageParam, wrapper);

        // 转换为DTO
        List<SysProjectDTO> projectDTOList = new ArrayList<>();
        for (SysProject project : projectPage.getRecords()) {
            SysProjectDTO projectDTO = new SysProjectDTO();
            BeanUtils.copyProperties(project, projectDTO);

            // 获取创建者信息
            User creator = userMapper.selectById(project.getCreateBy());
            if (creator != null) {
                projectDTO.setCreateByName( creator.getUsername());
            }

            projectDTOList.add(projectDTO);
        }

        // 创建返回结果
        Page<SysProjectDTO> result = new Page<>();
        result.setCurrent(projectPage.getCurrent());
        result.setSize(projectPage.getSize());
        result.setTotal(projectPage.getTotal());
        result.setRecords(projectDTOList);

        return result;
    }

    @Override
    public Page<SysProject> getUserCreatedProjects(Long userId, int page, int size) {
        // 创建分页对象
        Page<SysProject> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<SysProject> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysProject::getCreateBy, userId);
        wrapper.orderByDesc(SysProject::getCreateTime);
        return sysProjectMapper.selectPage(pageParam, wrapper);
    }
}
